from django.shortcuts import render, HttpResponse

# Create your views here.
from student.models import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


def Page(request, list):

    # 获取分页器对象
    paginator = Paginator(list, 5)

    # 获取前端返回选中页码,如果没有则page_number为默认值1,get获取的值为字符串
    page = request.GET.get('page', 1)
    currentPage = int(page)

    #  如果页数十分多时，换另外一种显示方式
    # 构建page_range
    max_page_count = 4
    max_page_count_half = int(max_page_count / 2)
    # 判断页数是否大于max_page_count
    if paginator.num_pages >= max_page_count:
        # 得出start位置
        if currentPage <= max_page_count_half:
            page_start = 1
            page_end = max_page_count + 1
        else:
            if currentPage + max_page_count_half + 1 > paginator.num_pages:
                page_start = paginator.num_pages - max_page_count
                page_end = paginator.num_pages + 1
            else:
                page_start = currentPage - max_page_count_half
                page_end = currentPage + max_page_count_half + 1
        page_range = range(page_start, page_end)
    else:
        page_range = paginator.page_range


    try:
        # print(page)
        list = paginator.page(page)
    except PageNotAnInteger:
        list = paginator.page(1)
    except EmptyPage:
        list = paginator.page(paginator.num_pages)


    return list, page_range